package org.gruposp2p.proyectokarma.controller

import java.util.Date;

import javax.persistence.Column;

import grails.converters.JSON
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.Authentication;
import org.gruposp2p.proyectokarma.domain.Comment;
import org.hibernate.search.annotations.Field;

class CommentController {
	
	def springSecurityService

	def save = {
		def userDetails = springSecurityService.principal
		def peer = Peer.get(userDetails.id)
		def document = null
		if (request.JSON.documentId){
			document = Document.get(request.JSON.documentId)
			if (!document) {
				response.status = 400  //Bad Request
				render message(code: 'proyectokarma.comment.saveInexistentDocument', 
					args:[request.JSON.documentId])
				return;
			}
		}
		def comment = new Comment(peerFrom:peer, document:document, 
			content:request.JSON.content);
		comment.save()
		def result = [id: comment.id, peerId:comment.peerFrom.id,
			content:comment.content]
		response.status = 201
		response.setHeader('Location', grailsApplication.config.grails.serverURL + '/comments/' + comment.id)
		render result as JSON
	}
	
	def show = {
		def commentList = []
		def commentsMap = new HashMap()
		if (params.ids?.size() > 0) {
			Comment.getAll(params.ids).collect {comment ->
				if (comment) commentList << comment;
			}
			if (commentList.size() == 0) {
				response.status = 404 //Not Found
				render message(code: 'proyectokarma.comment.commentNotFound', args:[params.ids])
				return
			}
		} else {
			commentList =  Comment.list(params)
			commentsMap.numberOfCommentsInSystem = Comment.count()
			commentsMap.numberOfCommentsInRequest = commentList.size()
			commentsMap.offset = params.offset
		}
		commentsMap.comments = commentList.collect {comment ->
			return [id: comment.id, peerFromId:comment.peerFrom.id, documentId:comment.document.id, 
				dateCreated:comment.dateCreated, content:comment.content]
		}
		render commentsMap as JSON
	}
	
	def update = {}
	
	def delete = {
		if (params.id) {
			def comment = Comment.get(params.id)
			if (comment) comment.delete()
			else {
				response.status = 404;
				render message(code: 'proyectokarma.comment.deleteNotFound', args:[params.id])
				return
			}
			response.status = 200;
			render message(code: 'proyectokarma.comment.deleteOK', args:[params.id])
			return
		} else {
			response.status = 400  //Bad Request
			render message(code: 'proyectokarma.comment.deleteBadRequest')
			return;
		}
	}

}
